package com.mailbox.mailbox.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mailbox.mailbox.domain.User;
import com.mailbox.mailbox.domain.Visitor;
import com.mailbox.mailbox.mapper.UserMapper;
import com.mailbox.mailbox.service.UserService;
import com.mailbox.mailbox.util.ResponseResult;
import com.mailbox.mailbox.util.SendEmail.VerCodeGenerateUtil;
import lombok.extern.slf4j.Slf4j;
import lombok.extern.slf4j.XSlf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * //手机(国内)   0?(13|14|15|17|18)[0-9]{9}
 * //邮箱    \w[-\w.+]*@([A-Za-z0-9][-A-Za-z0-9]+\.)+[A-Za-z]{2,14}
 *
* @author 栗守佳
* @description 针对表【user】的数据库操作Service实现
* @createDate 2022-05-15 08:45:17
*/
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService{
    /**
     * 盐值,用来MD5加密
     */
    private static final String SALT="!@#&(*!@&%(!@#!@#asdasdalhglasouiqnlknLKJLSJALIJVLZJXLKJCZLXKJ441321,mvbvbnvbsasdasd4a5s6d4a564q65w456qweqwe12312`12`123124/.zx,cx,cmnvba';sldslkdjgsldkjhqwpoeitqoiwuoqiweuoqwioiqweqwoiouo*(!(@*Y$!H@HUHFUHHKSH!(@*#HJKHKJASDAASD)!@(*JCLHLASAS+C+QASIGHLASD78456ASCAS**A-SDASD44QWDQAASDASDASD";

    /**
     * 找回密码的密钥,由校长亲自钦定
     */
    @Value("${authToken}")
    private String AUTH_TOKEN;

    @Resource
    PasswordEncoder passwordEncoder;

    /**
     * 邮箱正则表达式
     */
    public static final String EMAIL_REGEX="\\w[-\\w.+]*@([A-Za-z0-9][-A-Za-z0-9]+\\.)+[A-Za-z]{2,14}";

    /**
     * 正整数则表达式
     */
    public static final String NUMBER_REGEX="[1-9]\\d*";




    @Resource
    HttpServletRequest request;
    @Override
    public ResponseResult addAdmin(String username, String password, String chekPassword, String nickname) {
        //判断格式,账号格式,密码格式,大小,用正则表达式
        if(username.length()<4 || username.length()>20){
            return ResponseResult.error("账号长度错误");
        }
        if(password.length()<4 || password.length()>20){
            return ResponseResult.error("密码长度错误");
        }
        if(nickname.length()>26){
            return ResponseResult.error("昵称长度错误");
        }
        //正则表达式,不能让账号或密码中出现中文
        String validPattern="[\\u4e00-\\u9fa5]";
        Matcher matcher1= Pattern.compile(validPattern).matcher(username);
        Matcher matcher2= Pattern.compile(validPattern).matcher(password);
        if(matcher1.find()|| matcher2.find()){
            return ResponseResult.error("账号或密码不能有中文");
        }
        //判断添加的用户是否存在
        QueryWrapper<User> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("username",username);
        long count=this.count(queryWrapper);
        if(count>0){
            return ResponseResult.error("该用户已存在");
        }
        //创建时间
        Date date=new Date();
        SimpleDateFormat s=new SimpleDateFormat("yyyy-MM-dd HH:mm");
        String date1=s.format(date);
        //密码加密
        String newPassword= DigestUtils.md5DigestAsHex((SALT+password).getBytes());
        //创建实体
        User user=new User();
        user.setNickname(nickname);
        user.setUsername(username);
        user.setCreateTime(date1);
        user.setGrade(1);
        user.setPassword(passwordEncoder.encode(password));
        //保存到数据库
        this.save(user);
        //用户脱敏
        User safetyUser=getSafetyUser(user);

        return ResponseResult.success("添加用户成功",safetyUser);
    }

    @Override
    public ResponseResult adminLogin(String username, String password) {
        return ResponseResult.success("登陆成功");
    }

    @Override
    public User getSafetyUser(User originUser) {
        User safetyUser=new User();
        safetyUser.setUserId(originUser.getUserId());
        safetyUser.setUsername(originUser.getUsername());
        safetyUser.setCreateTime(originUser.getCreateTime());
        safetyUser.setNickname(originUser.getNickname());
        return safetyUser;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult updateUserPassword(String oldPassword, String newPassword,Integer userId) {
        User user= this.getById(userId);
        if(user==null){
            return ResponseResult.error("用户不存在");
        }
        String newPasswordMD5=passwordEncoder.encode(newPassword);
        if(!passwordEncoder.matches(oldPassword, user.getPassword())){
            return ResponseResult.error("旧密码不正确");
        }
        //确定要修改的实体部分
        User user1=new User();
        user1.setPassword(newPasswordMD5);
        //创建修改封装对象
        UpdateWrapper<User> userUpdateWrapper=new UpdateWrapper<>();
        //确定修改的条件,这里的eq("user_id",user.getUserId());意思是where user_id=#{user.getUserId()}
        userUpdateWrapper.eq("user_id",user.getUserId());
        this.update(user1,userUpdateWrapper);
        return ResponseResult.success("修改成功");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult findPassword(String authToken,String username,String newPassword) {
        QueryWrapper<User> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("username",username);
        User user= this.getOne(queryWrapper);
        if(user==null){
            return ResponseResult.error("用户不存在");
        }
        if(!authToken.equals(AUTH_TOKEN)){
            return ResponseResult.error("输入的密令错误,请重新输入");
        }
        if(newPassword.length()<4 || newPassword.length()>20){
            return ResponseResult.error("密码长度错误");
        }
        String newPasswordMD5=passwordEncoder.encode(newPassword);
        String validPattern="[\\u4e00-\\u9fa5]";
        Matcher matcher1= Pattern.compile(validPattern).matcher(username);
        if(matcher1.find()){
            return ResponseResult.error("账号或密码不能有中文");
        }
        User user1=new User();
        user1.setPassword(newPasswordMD5);
        //创建修改封装对象
        UpdateWrapper<User> userUpdateWrapper=new UpdateWrapper<>();
        //确定修改的条件,这里的eq("user_id",user.getUserId());意思是where user_id=#{user.getUserId()}
        userUpdateWrapper.eq("user_id",user.getUserId());
        this.update(user1,userUpdateWrapper);
        return ResponseResult.success("修改密码成功");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult updateNickname(String newNickname,Integer userId) {
        User user= this.getById(userId);
        if(user==null){
            return ResponseResult.error("用户不存在");
        }
        if(newNickname.length()>26){
            return ResponseResult.error("昵称长度错误");
        }
        User user1=new User();
        user1.setNickname(newNickname);
        //创建修改封装对象
        UpdateWrapper<User> userUpdateWrapper=new UpdateWrapper<>();
        //确定修改的条件,这里的eq("user_id",user.getUserId());意思是where user_id=#{user.getUserId()}
        userUpdateWrapper.eq("user_id",user.getUserId());
        this.update(user1,userUpdateWrapper);
        return ResponseResult.success("修改成功");
    }

    @Override
    public ResponseResult logout(Integer userId) {
        User user= this.getById(userId);
        if(user==null){
            return ResponseResult.error("用户不存在");
        }
        return ResponseResult.success("退出登录成功");
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult register(String phoneNumber, String password, String chekPassword, String nickname, String email,String username) {
        //判断账号格式
        if(username.length()<7||username.length()>11  && !email.matches(NUMBER_REGEX)){
            return ResponseResult.error("请输入正确的工号/学号");
        }
        //判断密码长度
        if(password.length()<6 || password.length()>20){
            return ResponseResult.error("密码长度错误");
        }
        //判断邮箱格式
        if(!email.matches(EMAIL_REGEX)){
            return ResponseResult.error("邮箱格式不正确");
        }
        //判断电话格式
        String phoneValid="0?(13|14|15|17|18)[0-9]{9}";
        boolean matcher1=phoneNumber.matches(phoneValid);
        if(!matcher1){
            return ResponseResult.error("电话格式不正确,请重新输入");
        }
        //判断账号是否被注册过
        QueryWrapper<User> queryWrapper0=new QueryWrapper<>();
        queryWrapper0.eq("username",username);
        long count0=this.count(queryWrapper0);
        if(count0>0){
            return ResponseResult.error("该账号已存在");
        }
        //判断添加的电话是否存在
        QueryWrapper<User> queryWrapper1=new QueryWrapper<>();
        queryWrapper1.eq("phone_number",phoneNumber);
        long count1=this.count(queryWrapper1);
        if(count1>0){
            return ResponseResult.error("该电话已存在");
        }
        //判断姓名格式
        String regex1 = "[\\u4E00-\\u9FA5]+";
        boolean matches2 = nickname.matches(regex1);
        if (!matches2 || nickname.length()>10){
            return ResponseResult.error("姓名格式错误");
        }
        //判断添加的邮箱是否存在
        QueryWrapper<User> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("email",email);
        long count=this.count(queryWrapper);
        if(count>0){
            return ResponseResult.error("该邮箱已存在");
        }
        //创建时间
        Date date=new Date();
        SimpleDateFormat s=new SimpleDateFormat("yyyy-MM-dd HH:mm");
        String date1=s.format(date);
        //创建实体
        User user=new User();
        user.setNickname(nickname);
        user.setUsername(username);
        user.setPassword(passwordEncoder.encode(password));
        user.setCreateTime(date1);
        user.setGrade(0);
        user.setEmail(email);
        user.setPhoneNumber(phoneNumber);
        //保存到数据库
        this.save(user);
        return ResponseResult.success("注册成功");
    }

    @Override
    public ResponseResult UserInfo(Integer userId) {
        QueryWrapper<User> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("user_id",userId);
        User user=this.getOne(queryWrapper);
        log.info("USER: "+user);
        if(user==null){
            return ResponseResult.error("用户不存在");
        }
        User user1=new User();
        user1.setUserId(user.getUserId());
        user1.setNickname(user.getNickname());
        user1.setUsername(user.getUsername());
        user1.setGrade(0);
        user1.setEmail(user.getEmail());
        user1.setPhoneNumber(user.getPhoneNumber());
        return ResponseResult.success("查询自己信息成功",user1);
    }


}




